import os
from typing import Optional, List


class KeywordProcessor:
    def __init__(self, keyword_file, result_file, export_file="exported_results.txt"):
        """
        初始化关键词处理器
        :param keyword_file: 关键词文件路径
        :param result_file: 结果文件路径
        :param export_file: 导出文件路径
        """
        self.keyword_file = keyword_file
        self.result_file = result_file
        self.export_file = export_file

    def _read_keywords(self):
        """读取关键词文件，跳过空行"""
        with open(self.keyword_file, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip()]

    def _get_processed_set(self):
        """获取已处理的关键词集合"""
        processed = set()
        if os.path.exists(self.result_file):
            with open(self.result_file, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line:
                        keyword = line.split(',', 1)[0]
                        processed.add(keyword)
        return processed

    def _save_safe(self, data):
        """安全保存实现"""
        temp_file = self.result_file + '.tmp'
        with open(temp_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(data))
        os.replace(temp_file, self.result_file)

    def _get_existing_results(self):
        """读取已有结果"""
        if not os.path.exists(self.result_file):
            return []
        with open(self.result_file, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip()]

    def get_results(self, keyword):
        """
        测试使用
        示例返回：[f"{keyword}_result1", ...]
        """
        return [
            f"{keyword}_result1",
            f"{keyword}_result2",
            f"{keyword}_result3"
        ]

    # 获取断点继续的关键词
    def get_todo_keywords(self) -> Optional[List[str]]:
        # 获取所有关键词
        all_keywords = self._read_keywords()

        # 获取已处理集合
        processed = self._get_processed_set()

        # 过滤未处理的关键词
        todo = [kw for kw in all_keywords if kw not in processed]
        return todo

    # 保存结果到文件
    def save_results(self, keyword, results: Optional[List[str]]):
        """"""
        if not results: return
        record: str = f"{keyword},{'/'.join(results)}"

        # 合并新旧结果
        all_data = self._get_existing_results()
        all_data.append(record)
        self._save_safe(all_data)

    def export(self, export_file=None):
        """导出结果到单独文件"""
        output_path = export_file or self.export_file
        with open(self.result_file, 'r', encoding='utf-8') as f_in, \
                open(output_path, 'w', encoding='utf-8') as f_out:

            for line in f_in:
                line = line.strip()
                if not line:
                    continue
                try:
                    _, results = line.split(',', 1)
                    for item in results.split('/'):
                        f_out.write(item + '\n')
                except ValueError:
                    continue


if __name__ == "__main__":
    # 使用示例
    processor = KeywordProcessor(
        keyword_file="keywords.txt",
        result_file="results.txt",
        export_file="output.txt"
    )

    # 保存结果
    processor.save_results("手表维修", processor.get_results("手表维修"))

    # 判断断点的词
    print(processor.get_todo_keywords())

    # 导出结果
    processor.export()

    print("处理完成")